package request

import (
	"bytes"
	"encoding/json"
	"github.com/pkg/errors"
	"io"
	"net/http"
	"net/url"
)

const (
	POST string = "POST"
	GET  string = "GET"
)

var EmptyHeader = make(map[string]string, 0)
var EmptyParams = make(map[string]string, 0)

func HttpRequest(
	urlStr string,
	method string,
	headers map[string]string,
	params map[string]string,
	data any,
	resp any) (*http.Response, error) {
	// 创建URL
	u, err := url.Parse(urlStr)
	if err != nil {
		return nil, err
	}

	// 添加查询参数
	query := u.Query()
	for k, v := range params {
		query.Set(k, v)
	}
	u.RawQuery = query.Encode()

	// 将数据编码为JSON
	buf := new(bytes.Buffer)
	if data != nil {
		b, err := json.Marshal(data)
		if err != nil {
			return nil, err
		}
		println(string(b))
		buf = bytes.NewBuffer(b)
	}

	// 创建请求
	req, err := http.NewRequest(method, u.String(), buf)

	if err != nil {
		return nil, err
	}

	for k, v := range headers {
		req.Header.Set(k, v)
	}

	if data != nil {
		req.Header.Set("Content-Type", "application/json")
	}

	// 发送请求
	rawResp, err := http.DefaultClient.Do(req)
	if err != nil {
		return nil, err
	}

	// 校验http返回状态码
	if rawResp.StatusCode != http.StatusOK {
		return nil, errors.Errorf("unexpected http response status: %d", rawResp.StatusCode)

	}

	// 反序列化http返回结果
	if resp != nil {
		bs, _ := io.ReadAll(rawResp.Body)
		defer rawResp.Body.Close()
		if errDecode := json.Unmarshal(bs, resp); errDecode != nil {
			return nil, errDecode
		}
	}
	// 返回响应，让调用者处理
	return rawResp, nil
}
